package com.example.myapplication4

import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.GridView
import android.widget.ImageView
import com.example.myapplication4.model.Card
import java.util.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity3 : AppCompatActivity() {
    private lateinit var cardGrid: GridView
    private val cards = mutableListOf<Card>()
    private var flippedCount = 0
    private var firstFlipped: Card? = null
    private var secondFlipped: Card? = null

    // 卡牌图片资源（使用系统默认图标，避免资源缺失）
    private val cardImages = intArrayOf(
        R.drawable.ic_launcher_foreground,
        R.mipmap.ic_launcher,
        R.mipmap.ic_launcher_round,
        R.drawable.ic_launcher_background
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main3)

        initCards()

        cardGrid = findViewById(R.id.card_grid)
        val cardAdapter = object : BaseAdapter() {
            override fun getCount(): Int = cards.size
            override fun getItem(position: Int): Any = cards[position]
            override fun getItemId(position: Int): Long = position.toLong()

            override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
                val iv = convertView as ImageView? ?: ImageView(this@MainActivity3).apply {
                    layoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        100
                    )
                    scaleType = ImageView.ScaleType.CENTER_CROP
                }
                val card = cards[position]
                iv.setImageResource(
                    if (card.isFlipped || card.isMatched) {
                        cardImages[card.id % cardImages.size]
                    } else {
                        R.drawable.ic_launcher_background // 卡牌背面
                    }
                )
                return iv
            }
        }
        cardGrid.adapter = cardAdapter


        cardGrid.setOnItemClickListener { _, _, position, _ ->
            val card = cards[position]
            if (canFlipCard(card)) {
                flipCard(card)
                checkMatch(cardAdapter)
            }
        }
        findViewById<Button>(R.id.restart_btn).setOnClickListener {
            initCards()
            cardAdapter.notifyDataSetChanged()
        }
    }
    private fun initCards() {
        cards.clear()
        for (i in 0 until 8) {
            cards.add(Card(i % 4)) // 每2张牌为一对
        }
        Collections.shuffle(cards) // 打乱顺序
        flippedCount = 0
        firstFlipped = null
        secondFlipped = null
    }

    // 判断是否可以翻牌
    private fun canFlipCard(card: Card): Boolean {
        return !card.isFlipped && !card.isMatched && flippedCount < 2
    }

    // 翻牌逻辑
    private fun flipCard(card: Card) {
        card.isFlipped = true
        flippedCount++
        when (flippedCount) {
            1 -> firstFlipped = card
            2 -> secondFlipped = card
        }
    }

    // 检查匹配并刷新界面
    private fun checkMatch(adapter: BaseAdapter) {
        if (flippedCount == 2) {
            if (firstFlipped?.id == secondFlipped?.id) {
                // 匹配成功
                firstFlipped?.isMatched = true
                secondFlipped?.isMatched = true
                adapter.notifyDataSetChanged() // 刷新界面
            } else {
                // 匹配失败，延迟翻回
                Handler().postDelayed({
                    firstFlipped?.isFlipped = false
                    secondFlipped?.isFlipped = false
                    adapter.notifyDataSetChanged() // 刷新界面
                }, 1000)
            }
            flippedCount = 0
            firstFlipped = null
            secondFlipped = null
        }
    }
}